<template>
  <div class="cx-container">
    <div class="factory-procurement-home">
      <div class="content-wrapper">
        <!-- 标题 -->
        <div class="section-title flex items-center justify-between">
          <h2>
            <el-icon class="title-icon"><OfficeBuilding /></el-icon>
            工厂收购
          </h2>
          <div class="more cursor-pointer" @click="goMore">
            <span>更多工厂</span>
            <span>>></span>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="3" animated />
        </div>

        <!-- 主要内容区域 -->
        <div v-else-if="procurementList.length > 0" class="main-content">
          <div class="main-factory">
            <el-row class="factory-list" :gutter="20">
              <el-col
                :xs="24"
                :sm="12"
                :md="6"
                :lg="6"
                :xl="6"
                v-for="company in procurementList.slice(0, 4)"
                :key="company.id"
              >
                <div class="factory-card">
                  <div class="card-image relative">
                    <el-image :src="defaultFactoryImg" fit="cover" class="w-full h-180px" />
                    <span
                      class="hot-badge absolute top-8px right-8px inline-flex items-center gap-6px bg-red-500 text-white text-12px font-700 px-10px py-4px rounded-16px"
                    >
                      <font-awesome-icon :icon="['fas', 'fire']" class="hot-icon" />
                      热门收购
                    </span>
                    <h3 class="card-title absolute left-16px bottom-12px m-0 text-white text-10px font-700">
                      {{ company.factoryName }}
                    </h3>
                  </div>
                  <div class="card-body">
                    <!-- 移除原先在正文中的标题，改为图片左下角覆盖显示 -->
                    <p class="card-address flex items-center gap-6px text-12px text-#888 m-0 mb-10px">
                      <el-icon class="addr-icon"><Location /></el-icon>
                      {{
                        (company.province || '') +
                          (company.city || '') +
                          (company.district || '') +
                          (company.addressDetail || '') || '地址待完善'
                      }}
                    </p>
                    <p class="card-address flex items-center gap-6px text-12px text-#888 m-0 mb-10px">
                      收购品种
                    </p>
                    <div class="card-tags flex gap-8px mb-12px">
                      <el-tag
                        v-for="name in getProductNames(company.procurementItems)"
                        :key="name"
                        size="small"
                        type="info"
                        >{{ name }}</el-tag
                      >
                    </div>
                    <div class="price-row flex items-center justify-between mb-12px">
                      <span class="price-label text-12px text-#999">收购价格</span>
                      <span class="price-value text-#e93323 font-700"
                        >￥{{ getPriceRange(company.procurementItems) }}/斤</span
                      >
                    </div>
                    <div class="card-footer mt-8px flex justify-center">
                      <el-button
                        type="success"
                        class="contact-btn w-90% mx-auto block"
                        :icon="Phone"
                        @click="onCopyPhone(company.mobilePhone)"
                      >
                        {{ isLoggedIn ? company.mobilePhone : maskPhone(company.mobilePhone) }}
                      </el-button>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        <!-- 空状态 -->
        <div v-else class="empty-state">
          <el-empty description="暂无工厂收购数据" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useFactoryProcurement } from '~/composables/useFactoryProcurement'
import { ElMessage } from 'element-plus'
import { navigateTo } from '#app'
import { OfficeBuilding, Phone, Location } from '@element-plus/icons-vue'
import defaultFactoryImg from '~/assets/images/factory-4.jpg'
import { useUserStore } from '~/stores/user'
import feedback from '~/utils/feedback'
import { useNuxtApp } from 'nuxt/app'

// 使用工厂收购组合式函数
const { loading, procurementList, fetchProcurementList } = useFactoryProcurement()

// 用户登录状态：参考 industry-belt 页面 uid 计算
const userStore = useUserStore()
const uid = computed(() => Number((userStore.userInfos && (userStore.userInfos.id || userStore.userInfos.userId)) || 0))
const isLoggedIn = computed(() => !!uid.value)

// 复制到剪贴板（含不安全上下文 fallback）
const nuxtApp = useNuxtApp()
const copyText = async (text: string) => {
  if (navigator.clipboard && navigator.clipboard.writeText) {
    await navigator.clipboard.writeText(text)
    return
  }
  // 兼容：非安全上下文或旧浏览器
  const textarea = document.createElement('textarea')
  textarea.value = text
  textarea.style.position = 'fixed'
  textarea.style.opacity = '0'
  document.body.appendChild(textarea)
  textarea.focus()
  textarea.select()
  try {
    document.execCommand('copy')
  } finally {
    document.body.removeChild(textarea)
  }
}

const onCopyPhone = async (phone: string | number) => {
  if (!isLoggedIn.value) {
    feedback.msgWarning('请先登录后再复制联系电话')
    if ((nuxtApp as any)?.$onHandlerLogin) (nuxtApp as any).$onHandlerLogin()
    return
  }
  const s = String(phone || '').trim()
  if (!s) return feedback.msgWarning('联系电话为空，无法复制')
  try {
    await copyText(s)
    feedback.msgSuccess('联系电话已复制到剪贴板')
  } catch (e) {
    feedback.msgError('复制失败，请稍后重试')
  }
}
console.log(isLoggedIn, 'isLoggedIn')
// 获取工厂名称首字母
const getFirstLetter = (name: string) => {
  if (!name) return '工'
  return name.charAt(0)
}

// 收购品种：从价格项中提取产品名称并去重
const getProductNames = (items: any[]) => {
  if (!Array.isArray(items)) return []
  const names = items.map((i) => (i?.productName || '').trim()).filter((s) => s && s.length > 0)
  return Array.from(new Set(names))
}

// 格式化更新时间
const formatUpdateTime = (time: string) => {
  if (!time) return '暂无'
  return new Date(time).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

// 页面加载时获取数据

const getPriceRange = (items: any[]) => {
  if (!items || items.length === 0) return '暂无'
  const prices = items.map((i) => Number(i?.purchasePrice)).filter((n) => !Number.isNaN(n))
  if (prices.length === 0) return '暂无'
  const min = Math.min(...prices)
  const max = Math.max(...prices)
  return min === max ? `${min}` : `${min}-${max}`
}

const goMore = () => navigateTo('/factory-procurement')

onMounted(async () => {
  try {
    await fetchProcurementList({ page: 1, limit: 4 })
  } catch (error) {
    console.error('获取工厂收购数据失败:', error)
    // ElMessage.error('获取工厂收购数据失败，请稍后重试')
  }
})

// 电话掩码
const maskPhone = (phone: string | number) => {
  const s = String(phone || '')
  return s && s.length >= 7 ? `${s.slice(0, 3)}****${s.slice(-4)}` : s || '电话待完善'
}
</script>

<style scoped lang="scss">
.cx-container {
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  padding: 20px 20px;
}

.factory-procurement-home {
  padding: 0 20px;

  width: 1400px;
  box-sizing: border-box;
  .content-wrapper {
    background-color: #ffffff;
    // border-radius: 8px;
    box-shadow: 0 2px 8px #0000001a;
    max-width: 1400px;
    width: 100%;
    margin: 0 auto;
    padding: 0 20px;
    box-sizing: border-box;
  }

  .section-title {
    padding-top: 20px;
    text-align: left;
    margin-bottom: 30px;

    h2 {
      font-size: 20px;
      font-weight: 700;
      color: #333;
      margin: 0;
      display: flex;
      align-items: center;
      gap: 8px;

      .title-icon {
        font-size: 24px;
        color: #e93323;
      }
    }

    .more {
      font-size: 16px;
      color: #666666;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      gap: 6px;
      font-weight: 500;
      letter-spacing: 0.2px;
      transition: color 0.2s ease;
    }
    .more:hover {
      color: #333333;
    }
  }

  .loading-container {
    background: #fff;
    border-radius: 8px;
    padding: 30px;
  }

  .main-content {
    .main-factory {
      background: #fff;
      // border-radius: 12px;
      // padding: 30px;
      // margin-bottom: 30px;
      // box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      display: flex;
      gap: 30px;

      .factory-left {
        flex: 2;

        .factory-header {
          display: flex;
          align-items: flex-start;
          gap: 20px;
          margin-bottom: 25px;

          .factory-logo {
            .logo-circle {
              width: 80px;
              height: 80px;
              border-radius: 50%;
              background: url('~/assets/images/reimage.png') no-repeat center center;
              background-size: 60px 60px;
              color: white;
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: 18px;
              font-weight: 600;
            }
          }

          .factory-info {
            flex: 1;

            .factory-name {
              font-size: 24px;
              font-weight: 700;
              color: #333;
              margin: 0 0 10px 0;
            }

            .factory-address {
              font-size: 14px;
              color: #666;
              margin: 0 0 15px 0;
            }

            .certification-badge {
              .badge {
                background: #e8f4fd;
                color: #1890ff;
                padding: 4px 12px;
                border-radius: 12px;
                font-size: 12px;
                font-weight: 500;
              }
            }
            .purchase-varieties {
              margin-top: 8px;
              font-size: 12px;
              .label {
                color: #999;
                margin-right: 6px;
              }
              .list {
                color: #666;
              }
            }
          }

          .price-table {
            .table-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 20px;
              gap: 10px;
              flex-wrap: wrap;

              h4 {
                font-size: 18px;
                font-weight: 600;
                color: #333;
                margin: 0;
              }

              .update-time {
                font-size: 12px;
                color: #999;
              }
              .price-range {
                font-size: 12px;
                color: #e93323;
                font-weight: 600;
              }
            }
          }

          .price-list {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 15px;

            th,
            td {
              padding: 12px;
              text-align: left;
              border-bottom: 1px solid #f0f0f0;
            }

            th {
              background: #fafafa;
              font-weight: 600;
              color: #333;
            }

            .price {
              color: #e93323;
              font-weight: 600;
              font-size: 16px;
            }
          }

          .table-footer {
            .disclaimer {
              font-size: 12px;
              color: #999;
              margin: 0 0 5px 0;
            }

            .contact-info {
              font-size: 12px;
              color: #666;
              margin: 0;
            }
          }
        }
      }

      /* 卡片列表：强制横向排列为四列 */
      .factory-list {
        border-radius: 12px;
        padding: 30px;
        margin-bottom: 30px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        /* 使用 Element Plus 栅格，容器无需强制设置 display */
      }

      .factory-card {
        background: #ffffff;
        border: 1px solid #ececec;
        border-radius: 12px;
        overflow: hidden;
        transition: transform 0.2s ease, box-shadow 0.2s ease;
        box-sizing: border-box;
        width: 100%;
        margin-bottom: 30px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      }

      .factory-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
      }

      /* 顶部大图：充满卡片宽度，固定高度并裁剪 */
      .card-image {
        position: relative;
        width: 100%;
        height: 180px;
        overflow: hidden;
        background: #fafafa;
      }
      .card-image :deep(.el-image) {
        width: 100%;
        height: 100%;
      }
      .card-image :deep(.el-image__inner) {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: block;
      }

      .factory-card .card-image .hot-badge {
        position: absolute !important;
        right: 10px !important;
        top: 10px !important;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        background: #e93323;
        color: #ffffff;
        border: none;
        border-radius: 16px;
        font-size: 12px;
        font-weight: 700;
        padding: 4px 10px;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
        z-index: 3;
        pointer-events: none;
      }
      .hot-icon {
        color: #ffffff !important;
      }
      .card-body {
        padding: 30px;
      }
      .factory-card .card-image .card-title {
        position: absolute !important;
        left: 16px !important;
        bottom: 12px !important;
        margin: 0;
        color: #ffffff;
        font-size: 18px;
        font-weight: 700;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        z-index: 2;
      }
      .card-address {
        font-size: 12px;
        color: #888;
        margin: 0 0 10px;
        display: flex;
        align-items: center;
        gap: 6px;
      }
      .addr-icon {
        color: #999;
        font-size: 16px;
      }
      .card-tags {
        display: flex;
        gap: 8px;
        margin-bottom: 12px;
      }
      .price-row {
        display: flex;
        align-items: center;
        justify-content: space-between !important;
        margin-bottom: 12px;
      }
      .price-label {
        font-size: 12px;
        color: #999;
      }
      .price-value {
        color: #e93323;
        font-weight: 700;
      }
      .card-footer {
        margin-top: 8px;
        display: flex;
        justify-content: center;
      }
      .contact-btn {
        width: 90% !important;
        display: block;
        margin: 0 auto !important;
        /* 使用 Element Plus 按钮的 CSS 变量确保颜色覆盖所有状态 */
        --el-button-bg-color: #20b455;
        --el-button-border-color: #20b455;
        --el-button-text-color: #ffffff;
        --el-button-hover-bg-color: #18a047;
        --el-button-hover-border-color: #18a047;
        --el-button-active-bg-color: #158a3d;
        --el-button-active-border-color: #158a3d;
      }
      .contact-btn:hover {
        /* 由 CSS 变量控制 hover，无需显式背景色 */
      }
    }
  }
}
.empty-state {
  background: #fff;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
}

.footer-note {
  text-align: center;
  margin-top: 20px;

  p {
    font-size: 12px;
    color: #999;
    margin: 0;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .factory-procurement-home {
    .main-content {
      .main-factory {
        flex-direction: column;
        gap: 20px;

        .factory-left {
          .price-table {
            .table-header {
              flex-direction: column;
              align-items: flex-start;
              gap: 10px;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 1200px) {
  .factory-procurement-home .main-content .factory-list {
    /* 两列 */
  }
  .factory-procurement-home .main-content .factory-list > .factory-card {
    flex: 0 0 calc((100% - 20px) / 2);
  }
}
@media (max-width: 768px) {
  .factory-procurement-home .main-content .factory-list {
    /* 一列 */
  }
  .factory-procurement-home .main-content .factory-list > .factory-card {
    flex: 0 0 100%;
  }
}
// 响应式：在小屏幕恢复为上下布局，图片100%宽
@media (max-width: 768px) {
  .factory-procurement-home {
    .main-content {
      .factory-card {
        display: block;
      }
      .card-image {
        width: 100%;
        min-width: 100%;
        height: 160px;
      }
      .card-body {
        width: 100%;
        padding: 30px;
      }
    }
  }
}
</style>
